﻿using System;
using System.Globalization;

namespace CyberConnect.Insteon.Messaging
{
    /// <summary>
    ///
    /// </summary>
    public struct MessageCommand : IEquatable<MessageCommand>
    {
        private readonly byte _Command1, _Command2;
        private readonly int _Commands;

        /// <summary>
        /// Command1 byte of an INSTEON responder message.
        /// </summary>
        public byte Command1 { get { return _Command1; } }

        /// <summary>
        /// Command2 byte of an INSTEON responder message.
        /// </summary>
        public byte Command2 { get { return _Command2; } }

        /// <summary>
        /// Commands of an INSTEON responder message as Int16.
        /// </summary>
        internal int Commands { get { return _Commands; } }

        public MessageCommand(int command)
        {
            this._Command1 = (byte)(command >> 8 & 0xFF);
            this._Command2 = (byte)(command & 0xFF);

            this._Commands = command;
        }

        public MessageCommand(byte command1, byte command2)
        {
            this._Command1 = command1;
            this._Command2 = command2;

            this._Commands = (command1 << 8 | command2);
        }

        public override bool Equals(object obj)
        {
            return obj == null ? false
                : !(obj is MessageCommand) ? false
                    : Equals((MessageCommand)obj);
        }

        public override int GetHashCode()
        {
            return this._Commands.GetHashCode();
        }

        public bool Equals(MessageCommand other)
        {
            return this._Commands == other.Commands;
        }

        public static bool operator ==(MessageCommand leftValue, MessageCommand rightValue)
        {
            return leftValue.Equals(rightValue);
        }

        public static bool operator !=(MessageCommand leftValue, MessageCommand rightValue)
        {
            return !(leftValue == rightValue);
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.CurrentCulture, "Command1:{0};Command2:{1};", _Command1.ToString("X2", CultureInfo.CurrentCulture), _Command2.ToString("X2", CultureInfo.CurrentCulture));
        }

        /// <summary>
        /// An empty MessageCommand.
        /// </summary>
        public static readonly MessageCommand Empty = new MessageCommand();

        public static explicit operator MessageCommand(int command)
        {
            return new MessageCommand(command);
        }
    }
}